package network;

import game.GameManager;

import java.net.*;
import java.io.*;

public class Receiver {
	private ServerSocket accepter;
	private boolean host;
	private String tableName;
	private PlayerJoined joiner;
	private GameManager manager;
	public Receiver() throws IOException {
		accepter = new ServerSocket(8888);
		//System.out.println("Server IP address: " + accepter.getInetAddress());
		host = false;
	}
	public Receiver(PlayerJoined joinedListener,
			GameManager waitingManager) throws IOException {
		this();
		joiner = joinedListener;
		manager = waitingManager;
		
	}
	public void makeHost(boolean b,String tableName){
		host = b;
		this.tableName = tableName;
	}
	public void listen() throws IOException {
		for (;;) {
			Socket s = accepter.accept();
			ReceiverProcessor echoer = new ReceiverProcessor(s,manager,joiner);
			if (host){
				echoer.makeHost(true, tableName);
			}
			System.out.println("Connection accepted from " + s.getInetAddress());
			echoer.start();
		}
	}
	public void closeListener(){
		try {
			accepter.close();
		} catch (IOException e) {
			System.out.print("Connection Failed to Close");
		}
	}
}